﻿namespace EyeOpen.IO.Ports
{
	public class Rs232
		: ChannelBase
	{
		public Rs232(IPort port, ILogger logger)
			: base(port, logger)
		{
			Type = ChannelType.Rs232;
			State = ChannelState.Closed;
		}

		public void ClearBuffers()
		{
			if (IsOpen)
			{
				return;
			}

			DiscardInBuffer();
			DiscardOutBuffer();
		}

		protected override void SendOnRs232Channel(string message)
		{
			ClearBuffers();

			var arrayByte = ConvertCommandStringToByteArray(message.ToUpper());

			Write(arrayByte, 0, arrayByte.Length);

			if (State != ChannelState.Connected)
			{
				State = ChannelState.Connected;
			}

			Logger.WriteLine("State: " + State);

			Logger.WriteLine("Sending message on " + Type + " channel...");
			Logger.WriteLine("--- " + message + " ---");
		}

		protected override void OpenRs232Channel()
		{
			if (IsOpen)
			{
				return;
			}

			Logger.WriteLine("Opening channel  " + Type + "...");

			State = ChannelState.Opening;
			Logger.WriteLine("State: " + State);

			Open();
			ClearBuffers();
		}

		protected override void CloseRs232Channel()
		{
			if (!IsOpen)
			{
				return;
			}

			Logger.WriteLine("Closing channel  " + Type + "...");

			State = ChannelState.Closing;
			Logger.WriteLine("State: " + State);

			ClearBuffers();
			Close();
		}
	}
}